/*
 * @Author: xiangxiaojun
 * @Date: 2022-04-21 09:43:02
 * @Descripttion: 简易视图
 */
import React, { useEffect, useState } from 'react';
import _ from 'lodash';
import { message, Popover, Typography } from 'antd';
import CompanyInfo from './CompanyInfo';
import { GlobalRegistry } from '@inbiz/core';
import { getMessage, TextWidget } from '@inbiz/react';
import { useGetThemeEffect } from '@inbiz/render';
import { getUserAvatarBytoken } from '../services';
import { userChooseTheme } from '../services';
import { webDataSourceClick, useApp, getOfficialPreview } from '@inbiz/utils';
import { useInbizRouter } from '@inbiz/hooks';
import { routerPrefix } from 'InbizConfig';
import '../style.less';

const systemThemeKeys = ['techblue', 'gray', 'deepskyblue', 'purple', 'deepblue'];
const prefixCls = 'inbiz-PersonalInfo';
const signOutLable = ['personalInfo.signout'];
const { Text } = Typography;

const SimpleView = (props: any) => {

  const appInfo = useApp();
  const { editInfo, signOut, userInfo, configList, getLangMessage, langs, random, themes } = props;
  const [visible, $setVisible] = useState(false); // 关于 公司信息弹窗
  const [showOption, $setShowOption] = useState(false); // 控制Popover 下拉组件
  const [currentTheme, $currentTheme] = props.hooksByTheme;
  const [currentLang, $currentLang] = useState(GlobalRegistry.getDesignerLanguage());
  const [openModal, $openModal] = useState<boolean>(true) //页面弹窗
  const history = useInbizRouter();

  const avatar = userInfo ? getUserAvatarBytoken(_.get(userInfo, 'IdentityId')) : '';

  // 获取筛选后的主题列表
  const themeList = () => {
    let result: any[] = [];
    let themeConfig = systemThemeKeys || [];
    const filterTheme = configList.filter((item: any) => item.tagName == 'theme');
    if (filterTheme.length) {
      themeConfig = filterTheme[0]?.themeConfig;
    }

    themes.forEach((item: any) => {
      if (themeConfig.some((theme: any) => theme == (item.langkey || item.OutId))) {
        result = [...result, item];
      }
    });

    return result;
  };

  // 菜单点击
  const onClick = (item: any) => {
    props.emit('onclick', item);
    if (item.tagName == 'setter') {
      // 点击设置
      editInfo && editInfo();
      $setShowOption(false);
      return false;
    }
    if (item.tagName == 'lang') {
      return false;
    }
    if (item.tagName == 'theme') {
      return false;
    }
    if (item.tagName == 'signout') {
      // 点击退出
      signOut && signOut();
      return false;
    }
    if (item.tagName == 'about') {
      // 点击关于
      $setVisible(true);
      $setShowOption(false);
      return false;
    }
    if (item.externalAddress) {
      $setShowOption(false);
      if (item.openMode === 1) {
        open(item)
      } else {
        window.open(item.linkAddress);
      }
    } else if (item.page) {
      $setShowOption(false);
      if (item.openMode === 1) {
        open(item, true)
      } else if (item.openMode === 2) {
        let route = String(item.page).slice(0, String(item.page).indexOf(','))
        window.open(`${location.origin}${location.pathname}${location.search}#${routerPrefix}${route}`)
      } else {
        webDataSourceClick(history, item);
      }
    } else {
      return message.warn(getMessage('personalInfo.setPage'));
    }
  };

  // 多语言设置
  const onChangeLanguage = (item: any, title: any) => {
    props.emit?.('onClick', getMessage(title), item)
    $currentLang(item.Code);
    getLangMessage(item.Code);
    // TODO 待实现
  };

  // 主题
  const onChangeTheme = async (row: any, title: any) => {
    $currentTheme(row.OutId || row.id);
    props.emit?.('onClick', getMessage(title), row)
    const opt = {
      theme: row.OutId || row.id,
      siteOutId: appInfo?.SiteInfo?.OutId,
    };
    const data = await userChooseTheme(opt);
    if (!data) return;
  };

  const commonStyle = {
    fontSize: 'var(--inbiz-font-size-base)',
  };

  //弹窗打开页面 
  const open = (item: any, isPage?: boolean) => {
    const src: any = {}
    if (isPage) {
      let route = String(item.page).slice(0, String(item.page).indexOf(','))
      src.route = route
    } else {
      src.src = item.linkAddress
      src.style = { border: 'none' }
    }

    const modal = props.inbiz.loadPage({
      href: src,
      mount: {
        title: getMessage(item.title),
        width: item.windowWidth,
        visible: openModal,
        style: { height: item.windowHeight },
        className: `${prefixCls}-openMoal`,
        cancelText: getMessage('personalInfo.cancel'),
        okText: getMessage('personalInfo.ok'),
        onCancel: function () {
          props.emit('onclick', {
            type: 'cancel',
            src,
          })
          modal.hide()
        },
        onOk: function () {
          props.emit('onclick', {
            type: 'ok',
            src,
          })
          modal.hide()
        }
      }
    });
  }

  // 操作面板
  const content = () => {
    const filterList = configList.filter((item: any) => !item.hide);
    const topList = filterList.filter((item: any) => !item.tagName || item.tagName != 'signout');
    const lastList = filterList.filter((item: any) => item.tagName == 'signout');
    return (
      <div className={`${prefixCls}-simpleview-option`}>
        <div className={`simpleview-top`}>
          <div className={`simpleview-top-head`}>
            <img src={`${avatar}&r=${random}`} />
          </div>
          <div className="simpleview-right">
            <div
              className="simpleview-right-name"
              style={commonStyle}
              title={_.get(userInfo, 'Name')}
            >
              {_.get(userInfo, 'Name')}
            </div>
            <div
              className="simpleview-right-position"
              style={{
                fontSize: 'var(--inbiz-font-size-base)',
                color: 'var(--inbiz-color-secondary-text)',
              }}
            >
              {_.get(userInfo, 'MainDepartmentName')}
            </div>
          </div>
        </div>
        <div className="simpleview-ul">
          {configList &&
            [...topList, ...lastList].map((item, index) => {
              let childrenView: any = [];
              if (item.tagName == 'lang') {
                childrenView = (
                  <div className="simpleview-ul-box">
                    <div className={`simpleview-li-box`}>
                      {langs.map((ele) => {
                        if (ele.Code == 'en') {
                          ele.Code = 'en-us';
                        }
                        return (
                          <div
                            onClick={() => onChangeLanguage(ele, item.title)}
                            className={`simpleview-li-children ${(currentLang == ele.Code?.toLocaleLowerCase() || currentLang == ele.Code) ? 'simpleview-li-children-selected' : ''
                              } `}
                            key={ele.Code}
                          >
                            {ele.Name}
                          </div>
                        );
                      })}
                    </div>
                  </div>
                );
              }
              if (item.tagName == 'theme') {
                childrenView = (
                  <div className="simpleview-ul-box">
                    <div className={`simpleview-li-box`}>
                      {themeList().map((ele: any) => (
                        <div
                          onClick={() => onChangeTheme(ele, item.title)}
                          className={`simpleview-li-children ${currentTheme == (ele.OutId || ele.id)
                            ? 'simpleview-li-children-selected'
                            : ''
                            } `}
                          key={ele.langkey || ele.OutId}
                        >
                          <span style={{ backgroundColor: ele.color || ele.Color }}></span>
                          <TextWidget>
                            {ele.langkey ? `themeconfig.${ele.langkey}` : ele.Name}
                          </TextWidget>
                        </div>
                      ))}
                    </div>
                  </div>
                );
              }
              return (
                <Popover
                  key={index}
                  placement="leftTop"
                  content={childrenView}
                  trigger="hover"
                  overlayClassName={`${prefixCls}-Popover-c`}
                >
                  {signOutLable.includes(item.title) ? (
                    <>
                      <div className="loginoutBoxLine"></div>
                      <div
                        className={`simpleview-li loginoutBox`}
                        key={index}
                        onClick={() => onClick(item)}
                      >
                        <div style={{ flex: 1, fontSize: 'var(--inbiz-font-size-base)' }}>
                          <TextWidget>{item.title}</TextWidget>
                        </div>
                        {item.children ? <div className="simpleview-li-arr" /> : null}
                      </div>
                    </>
                  ) : (
                    <div className={'simpleview-li'} key={index} onClick={() => onClick(item)}>
                      <div style={{ flex: 1, fontSize: 'var(--inbiz-font-size-base)' }}>
                        <TextWidget>{item.title}</TextWidget>
                      </div>
                      {item.children ? <div className="simpleview-li-arr" /> : null}
                    </div>
                  )}
                </Popover>
              );
            })}
        </div>
      </div>
    );
  };

  return (
    <div className={`${prefixCls}-simpleview`}>
      <Popover
        placement="bottomLeft"
        content={content}
        overlayStyle={{ paddingRight: 20 }}
        trigger="hover"
        getPopupContainer={(node) => document.body}
        visible={showOption}
        onVisibleChange={(flag) => $setShowOption(flag)}
        overlayClassName={`${prefixCls}-Popover`}
      >
        <div className={`${prefixCls}-simpleview-infobox`}>
          <div className={`${prefixCls}-simpleview-head`}>
            {avatar ? <img className={`${prefixCls}-simpleview-head-img`} src={`${avatar}&r=${random}`} /> : null}
          </div>
          <div className={`${prefixCls}-simpleview-name`} title={_.get(userInfo, 'Name')}>
            <Text ellipsis style={{ ...commonStyle }}>
              {_.get(userInfo, 'Name')}
            </Text>
          </div>
        </div>
      </Popover>
      {/* <CompanyInfo visible={visible} onCancel={() => $setVisible(false)} /> */}
    </div>
  );
};
export default SimpleView;
